package com.red.service.impl;

import com.red.mapper.HouseMapper;
import com.red.mapper.OrderMapper;
import com.red.pojo.Result;
import com.red.pojo.entity.House;
import com.red.pojo.entity.Order;
import com.red.service.IOrderService;
import com.red.util.HttpStatusUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private HouseMapper houseMapper;

    @Override
    public int insertOrder(Order order) {
        return orderMapper.insertOrder(order);
    }

    @Override
    public List<Order> selectOrderList(Order order, int page, int size) {
        int offset = (page - 1) * size;
        return orderMapper.selectOrderList(order, offset, size);
    }

    /**
     * 获取指定房屋处于洽谈状态的订单
     */
    @Override
    public Order selectOrderOfHouseWhichFighting(int houseId) {
        return orderMapper.selectOrderByHouseId(houseId);
    }

    @Override
    public int selectOrderCount(Order order) {
        return orderMapper.selectOrderCount(order);
    }

    @Override
    public Order selectOrderByID(int id) {
        return orderMapper.selectOrderByID(id);
    }

    @Override
    public Result selectOrderListV2(int userId) {
        return new Result(HttpStatusUtil.SUCCESS, "获取成功", orderMapper.selectOrderListV2(userId));
    }

    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    @Override
    public int deleteOrderByID(int id) {
        return orderMapper.deleteOrderByID(id);
    }

    @Override
    public Result payOrder(int userId, int orderId) {
        Order order = orderMapper.selectOrderByID(orderId);

        if (order == null) {
            return Result.error("订单不存在");
        }

        if (order.getUserId() != userId) {
            return Result.error("订单异常");
        }

        order.setStatus("1");

        if (orderMapper.updateOrder(order) > 0) {
            House house = new House();
            house.setHouseId(order.getHouseId());
            house.setStatus("1");

            if (houseMapper.updateHouse(house) > 0) {
                return Result.success("支付成功");
            } else {
                return Result.success("房源异常");
            }
        } else {
            return Result.error("支付失败");
        }
    }
}
